package com.greedcaves.autohelper;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.core.app.NotificationCompat;

import java.util.Random;

public class AutoHelperService extends Service {

    private static final String CHANNEL_ID = "auto_helper_channel";
    private static final int NOTIFICATION_ID = 1;

    private WindowManager windowManager;
    private View floatingView;
    private WindowManager.LayoutParams params;
    
    private boolean isRunning = false;
    private Handler handler;
    private Runnable autoTaskRunnable;
    private Random random;

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
        startForeground(NOTIFICATION_ID, createNotification());
        
        handler = new Handler(Looper.getMainLooper());
        random = new Random();
        
        // 初始化悬浮窗
        initFloatingView();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "贪婪洞窟自动助手",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    private Notification createNotification() {
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("贪婪洞窟自动助手")
                .setContentText("自动操作服务正在运行")
                .setSmallIcon(R.mipmap.ic_launcher)
                .build();
    }

    private void initFloatingView() {
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        floatingView = inflater.inflate(R.layout.floating_control, null);

        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                        WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                PixelFormat.TRANSLUCENT
        );

        params.gravity = Gravity.TOP | Gravity.START;
        params.x = 0;
        params.y = 100;

        final ToggleButton btnToggle = floatingView.findViewById(R.id.btn_toggle);
        final TextView tvStatus = floatingView.findViewById(R.id.tv_status);

        btnToggle.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                startAutoTask();
                tvStatus.setText("运行中");
            } else {
                stopAutoTask();
                tvStatus.setText("已停止");
            }
        });

        // 设置悬浮窗拖拽
        floatingView.findViewById(R.id.floating_container).setOnTouchListener(new View.OnTouchListener() {
            private int initialX;
            private int initialY;
            private float initialTouchX;
            private float initialTouchY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialX = params.x;
                        initialY = params.y;
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        params.x = initialX + (int) (event.getRawX() - initialTouchX);
                        params.y = initialY + (int) (event.getRawY() - initialTouchY);
                        windowManager.updateViewLayout(floatingView, params);
                        return true;
                }
                return false;
            }
        });

        windowManager.addView(floatingView, params);
    }

    private void startAutoTask() {
        if (isRunning) return;
        isRunning = true;

        autoTaskRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isRunning) return;

                try {
                    // 执行自动操作逻辑
                    performAutoOperations();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // 继续下一轮任务
                handler.postDelayed(this, 1000); // 每秒执行一次
            }
        };

        handler.post(autoTaskRunnable);
    }

    private void stopAutoTask() {
        isRunning = false;
        if (handler != null && autoTaskRunnable != null) {
            handler.removeCallbacks(autoTaskRunnable);
        }
    }

    private void performAutoOperations() {
        // 1. 检测屏幕上是否有怪物
        boolean hasMonster = detectMonster();
        
        if (hasMonster) {
            // 2. 如果有怪物，执行攻击操作
            attackMonster();
        } else {
            // 3. 如果没有怪物，移动寻找怪物
            moveRandomly();
        }

        // 4. 检测并使用药水（如果生命值低）
        if (isHealthLow()) {
            useHealthPotion();
        }
    }

    private boolean detectMonster() {
        // 这里应该实现图像识别逻辑，检测屏幕上是否有怪物
        // 简化版本，返回随机结果模拟
        return random.nextBoolean();
    }

    private void attackMonster() {
        // 模拟点击攻击按钮
        // 实际应用中应该通过坐标模拟点击
        int attackX = 600; // 攻击按钮X坐标（需要根据实际游戏调整）
        int attackY = 1800; // 攻击按钮Y坐标（需要根据实际游戏调整）
        simulateClick(attackX, attackY);
    }

    private void moveRandomly() {
        // 随机移动方向
        int directions[][] = {
                {300, 2000}, // 上
                {600, 2000}, // 右
                {900, 2000}, // 下
                {1200, 2000} // 左
        };
        int[] direction = directions[random.nextInt(directions.length)];
        simulateClick(direction[0], direction[1]);
        
        // 点击移动一段时间
        try {
            Thread.sleep(1000 + random.nextInt(2000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private boolean isHealthLow() {
        // 检测生命值是否低
        // 简化版本，随机返回
        return random.nextFloat() < 0.2f; // 20%概率需要使用药水
    }

    private void useHealthPotion() {
        // 点击药水位置
        int potionX = 1500; // 药水位置X坐标（需要根据实际游戏调整）
        int potionY = 1800; // 药水位置Y坐标（需要根据实际游戏调整）
        simulateClick(potionX, potionY);
    }

    private void simulateClick(int x, int y) {
        // 实际应用中需要使用AccessibilityService或root权限来模拟点击
        // 这里只是占位方法
        try {
            // 通过反射或其他方式执行点击
            // 注意：在实际应用中，需要使用更复杂的方法来实现点击
            System.out.println("模拟点击: (" + x + ", " + y + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopAutoTask();
        if (floatingView != null && windowManager != null) {
            windowManager.removeView(floatingView);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}